package com.yanwq.nwa.im;

import android.content.Intent;
import android.util.Log;

import com.yanwq.nwa.MApplication;

/**
 * Created by dodoca_android on 2017/3/31.
 */

public class Connector {
    static private Connector instance;

    synchronized static private void syncInit() {
        if (instance == null) {
            instance = new Connector();
        }
    }

    static public Connector getInstance() {
        syncInit();
        return instance;
    }

    private ConnectionStat stat;

    private Connector() {
        stat = ConnectionStat.IDLE;
    }

    public void heartbeat() {
        MApplication.getContext().startService(new Intent(MApplication.getContext(), PingService.class));
    }

    public void connect() {
        if (stat != ConnectionStat.IDLE) {
            return;
        }

        new Thread(new Runnable() {
            @Override
            synchronized public void run() {
                setStat(Connector.ConnectionStat.CONNECTING);
                try {
                    Log.i("WebSocketClientRunner", "connect");
                    MApplication.getWebSocketClientRunner().run();
                } catch (Exception e) {
                    e.printStackTrace();
                    try {
                        Thread.sleep(10 * 1000);
                    } catch (InterruptedException ie) {
                        ie.printStackTrace();
                    }
                    Thread.currentThread().interrupt();
                    Log.i("WebSocketClientRunner", "reconnect");
                    new Thread(this).start();
                }
            }
        }).start();
    }

    public void disconnect() {
        if (stat == ConnectionStat.IDLE) {
            return;
        }
        MessageMgr.getInstance().sendClose();
    }

    public ConnectionStat getStat() {
        return stat;
    }

    public void setStat(ConnectionStat stat) {
        this.stat = stat;
    }

    public enum ConnectionStat {
        IDLE, CONNECTING, CONNECTED
    }
}